"""
RedFlag-TC000041   分类道具下载
分类道具下载场景
注意有四个道具需要手动查看1.国潮季：哪吒/黑猫警长；2.场景：第二个生日快乐；3.龙凤呈祥：龙凤呈祥
"""
__author__ = "ldm"

import sys
import os
import yaml

# 获取当前脚本所在目录.py
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取上级目录.air
parent_dir = os.path.dirname(current_dir)
# 获取上级目录air
grandparent_dir = os.path.dirname(parent_dir)
# 获取和air目录平级的conf、testcase目录路径
conf_dir = os.path.join(grandparent_dir, 'conf')
testcase_dir = os.path.join(grandparent_dir, 'testcase')
# 将conf、testcase目录添加到sys.path
sys.path.append(conf_dir)
sys.path.append(testcase_dir)

from PageFunction import CameraVideoShooter
from elements import *
auto_setup(__file__)

poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
log("-------------------------读取yaml文件----------------------------------------------")
# 读取YAML文件
def read_yaml(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
        return data
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在")
        raise
    except yaml.YAMLError as e:
        print(f"解析YAML文件 {file_path} 出错: {str(e)}")
        raise
log("-------------------------封装的操作方法----------------------------------------------")
"""
获取调用元素的父级-子级
判断所需元素的下级节点数量
获取目标节点的下级节点数量
进行断言
"""
def assert_download_success(shooter, prop_node, prop_scene_name):
    parent_node = prop_node.parent()
    parent_children = parent_node.children()
    if len(parent_children) == 0:
        print(f"断言失败：父节点没有子节点，元素：{prop_scene_name}")
        return
    first_child = parent_children[0]
    first_child_children = first_child.children()
    if len(first_child_children) < 3:
        print(f"道具已下载，元素：{prop_scene_name}")
        # 跳到断言部分
        text = shooter.get_child_count(first_child)
        shooter.assert_texts_equal(text, 1, "断言失败，子节点数量与预期数量不一致，下载失败")
        print(f" {prop_scene_name} 场景下载成功")
        return

    first_child_children = first_child.children()[2]
    shooter.wait_for_element_disappearance(first_child_children, 20)
    text = shooter.get_child_count(first_child)
    shooter.assert_texts_equal(text, 1, "断言失败，子节点数量与预期数量不一致，下载失败")
    print(f" {prop_scene_name} 场景下载成功")


log("-------------------封装调用yaml文件中download_props_data列表的方法----------------------------")
def click_elements(shooter, data):
    """
    从yaml文件中引用元素
    针对正常元素download_props_data列表中的元素
    判断如果没有找到一级分类节点就进行滑动操作
    判断如果没有找到二级分类元素就进行滑动操作
    :param shooter:
    :param data: 从yaml文件中引用的元素
    :return:
    """
    # 点击一级分类元素
    for category, props in data['download_props_data'].items():
        element = shooter.get_element_by_text(props['prop']['text'])
        if not element.exists():
            print(f"未找到一级分类元素 {props['prop']['text']}，进行滑动操作")
            shooter.swipe_screen((0.85, 0.67), (0.3, 0.67))
            element = shooter.get_element_by_text(props['prop']['text'])
            if not element.exists():
                print(f"滑动后仍未找到一级分类元素 {props['prop']['text']}")
                continue
        try:
            shooter.click_element_text(element)
        except Exception as e:
            print(f"点击一级分类元素 {props['prop']['text']} 失败: {str(e)}")

        # 点击二级分类元素
        for item in props['items']:
            element = shooter.get_element_by_text(item['text'])
            if not element.exists():
                print(f"未找到二级分类元素 {item['text']}，进行滑动操作")
                shooter.swipe_screen((0.82, 0.9), (0.82, 0.8))
                element = shooter.get_element_by_text(item['text'])
                if not element.exists():
                    print(f"滑动后仍未找到二级分类元素 {item['text']}")
                    continue
            try:
                shooter.click_element_text(element)
                # 点击二级元素后调用断言方法
                assert_download_success(shooter, element, item['text'])
            except Exception as e:
                print(f"点击二级分类元素 {item['text']} 失败: {str(e)}")

log("-------------------封装的调用yaml文件中download_abnormal_props_data列表的方法----------------------------")
def click_abnormal_elements(shooter, data):
    """
    从yaml文件中引用元素
    针对部分元素download_abnormal_props_data这个列表中的元素
    判断如果没有找到一级分类节点就进行滑动操作
    进入一节节点后直接进行滑动操作
    点击二级节点
    :param shooter:
    :param data: 从yaml文件中引用的元素
    :return:
    """
    # 点击一级分类元素
    for category, props in data['download_abnormal_props_data'].items():
        element = shooter.get_element_by_text(props['prop']['text'])
        while not element.exists():
            print(f"未找到一级分类元素 {props['prop']['text']}，进行滑动操作")
            shooter.swipe_screen((0.85, 0.67), (0.3, 0.67))
            element = shooter.get_element_by_text(props['prop']['text'])
        try:
            shooter.click_element_text(element)
            # 点击一级元素分类后执行滑动操作
            shooter.swipe_screen((0.82, 0.9), (0.82, 0.5))
        except Exception as e:
            print(f"点击一级分类元素 {props['prop']['text']} 失败: {str(e)}")

        # 点击二级分类元素
        for item in props['items']:
            element = shooter.get_element_by_text(item['text'])
            while not element.exists():
                print(f"未找到二级分类元素 {item['text']}，进行滑动操作")
                shooter.swipe_screen((0.82, 0.9), (0.82, 0.8))
                element = shooter.get_element_by_text(item['text'])
            try:
                shooter.click_element_text(element)
                # 点击二级元素后调用断言方法
                assert_download_success(shooter, element, item['text'])
            except Exception as e:
                print(f"点击二级分类元素 {item['text']} 失败: {str(e)}")

log("-------------------用例执行层----------------------------")
"""
前置操作
进入相机拍摄
点击道具
读取yaml文件路径
调用click_elements方法执行测试用例
执行完后关闭APP
重新打开APP
进入相机拍摄
调用click_abnormal_elements执行测试用例
关闭APP
"""
shooter = CameraVideoShooter()
shooter.enter_photograph()
shooter.click_element(shooting_page_prop)

yaml_file_path = os.path.join(conf_dir, 'TC000041_prop_element_positioning.yaml')
try:
    yaml_data = read_yaml(yaml_file_path)
    click_elements(shooter, yaml_data)
    # 关闭APP
    stop_app(UGC_package_name)
    # 重新打开
    sleep(5.0)
    shooter.enter_photograph()
    sleep(1.0)
    shooter.click_element(shooting_page_prop)
    shooter.wait_for_element_appearance(shooting_page_select_prop, 20)
    click_abnormal_elements(shooter, yaml_data)
    # 关闭APP
    stop_app(UGC_package_name)
except:
    print("在读取或处理YAML数据时出现错误")